'use client';

import React, { useEffect, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useAuthStore } from '@/store/useAuthStore';
import MainLayout from '@/components/layout/MainLayout';

const CallbackPage = () => {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { handleCallback, isAuthenticated, isLoading, error } = useAuthStore();
  const [localError, setLocalError] = useState<string | null>(null);

  useEffect(() => {
    const processCallback = async () => {
      try {
        const code = searchParams.get('code');
        if (!code) {
          setLocalError('未收到授权码');
          return;
        }

        await handleCallback(code);
        router.push('/repositories');
      } catch (err) {
        console.error('处理回调失败', err);
        setLocalError(err instanceof Error ? err.message : '处理回调失败');
      }
    };

    if (!isAuthenticated) {
      processCallback();
    } else {
      router.push('/repositories');
    }
  }, [searchParams, handleCallback, router, isAuthenticated]);

  return (
    <MainLayout>
      <div className="min-h-screen bg-gray-50 dark:bg-gray-900 flex flex-col justify-center py-12 sm:px-6 lg:px-8">
        <div className="sm:mx-auto sm:w-full sm:max-w-md">
          <h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900 dark:text-white">
            处理登录中
          </h2>
          <p className="mt-2 text-center text-sm text-gray-600 dark:text-gray-400">
            请稍候，我们正在处理您的登录请求
          </p>
        </div>

        <div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
          <div className="bg-white dark:bg-gray-800 py-8 px-4 shadow sm:rounded-lg sm:px-10">
            {(error || localError) && (
              <div className="mb-4 bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative dark:bg-red-900 dark:text-red-200 dark:border-red-800" role="alert">
                <strong className="font-bold">错误：</strong>
                <span className="block sm:inline">{error || localError}</span>
              </div>
            )}

            {isLoading ? (
              <div className="flex flex-col items-center justify-center py-6">
                <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-green-500"></div>
                <p className="mt-4 text-gray-600 dark:text-gray-400">正在处理登录，请稍候...</p>
              </div>
            ) : (
              <div className="text-center py-6">
                {!error && !localError && (
                  <>
                    <svg className="mx-auto h-12 w-12 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                    <p className="mt-4 text-gray-600 dark:text-gray-400">登录成功，正在跳转...</p>
                  </>
                )}
                {(error || localError) && (
                  <button
                    onClick={() => router.push('/login')}
                    className="mt-4 inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500"
                  >
                    返回登录页
                  </button>
                )}
              </div>
            )}
          </div>
        </div>
      </div>
    </MainLayout>
  );
};

export default CallbackPage;